#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Blueprint,render_template, request, session,abort
from sqlalchemy import or_
from ..database import Article
from ..secure import login_required

from urllib.parse import unquote, quote


bp = Blueprint('kw', __name__, url_prefix="/kw")

@bp.route('/', methods=["GET", "POST"])
@bp.route('<int:page>')
# @login_required
def kw_search(page=1):
    '''关键字搜索文章：
        1.支持地址栏输入(get请求)
        2.支持输入框输入(post请求)
        3.支持分页查询(get请求)
    '''

    # 设置默认请求标识为post
    method = "latest_post"

    if request.method == "POST":
        # 如果是post请求，说明是表单提交的，那么用session保存最近请求的关键字,
        # 用于分页查询时还是查询上一次输入的关键字的内容
        print(request.form.get('keyboard'))
        session['latest_post'] = request.form.get('keyboard')

    if request.method == "GET":
        # 如果是get请求，说明是从地址栏提交的或者是点击了分页按钮提交的，下面将区分是哪一种提交
        
        # 重置请求标识为get
        method = "latest_get"
        
        # 获取从地址栏得到的关键字
        s=request.query_string
        # print(s, type(s), len(s))
        # print(s,'ss')

        if not len(s):
            return abort(404,'missing parameters, such as /kw/?s=python')

        # 将地址栏的bytes(b's=python')解码为utf-8格式，再进行字符串拆分
        s = s.decode("utf-8").split("=")
        if s[0]=="s" and bool(s[1]):
            # 规定输入的格式是——>http://xxx.com/kw/?s=python
            # 把关键字中含有形如：%25E6%B255%258B%25E8%AF%2595的中文字符转为中文，再存入session
            session['latest_get'] = unquote(s[1])
    # 为了避免
    url_for = "kw.kw_search"
    rule = or_(*[Article.title.like("%"+kw+"%") for kw in session.get(method).split(" ")],
        *[Article.tag.like("%"+kw+"%") for kw in session.get(method).split(" ")],
        *[Article.content.like("%"+kw+"%") for kw in session.get(method).split(" ")])

    pagination = Article.query.filter(rule).order_by(Article.publish_time.desc()).paginate(page=page,per_page=10)
    

    return render_template('/pages/kw_search.html', data=pagination, url=url_for)


